#!/bin/bash

set -e
set -o pipefail

git fetch --tags

SCRIPTS_DIR="$( dirname "$(readlink -f "$0")" )"

publishable_paths=$(node "$SCRIPTS_DIR/get-publishable-paths-from-semver-tags.mjs" | sed -E -e '/^ *$/d')

if [ -z "$publishable_paths" ]; then
    echo "Nothing to publish."
    exit 0
fi

if [ -z "${NPM_AUTH_TOKEN}" ]; then
    echo "No NPM auth token available. Check the \$NPM_AUTH_TOKEN environment variable."
    exit 1
fi

# see https://pnpm.io/cli/config
pnpm config set //registry.npmjs.org/:_authToken "${NPM_AUTH_TOKEN}"

for path in $publishable_paths; do
    pushd "$path"
    echo "Attempting to publish package at path '$path'"
    "$SCRIPTS_DIR/circle-publish-npm"
    popd
done
